package com.advice;


import com.dto.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import javax.servlet.http.HttpServletResponse;

/**
 * @Description 将控制层的返回响应状态全局设置
 */
@Slf4j
@RestControllerAdvice(basePackages = "com.kingpro.controller")
public class CommonRestControllerAdvice implements ResponseBodyAdvice {
    @Autowired
    private HttpServletResponse resp;

    /**
     * 用于决定这个全局的Controller切面是否要作用到对应的控制器以及控制器方法中去
     *
     * @param methodParameter
     * @param aClass
     * @return
     */
    @Override
    public boolean supports(MethodParameter methodParameter, Class aClass) {
        //TODO:这两个参数的格式可以通过Debug来查看……
        return true;
    }

    /**
     * 如果有异常，会先处理完异常，再执行这里的方法
     *
     * @param o
     * @param methodParameter
     * @param mediaType
     * @param aClass
     * @param serverHttpRequest
     * @param serverHttpResponse
     * @return
     */
    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        if (null != o) {
            JsonResult result = (JsonResult) o;
            resp.setStatus(result.getCode());
            return result;
        }
        return null;
    }
}
